package pers.jason.wppm.security.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import pers.jason.wppm.security.authentication.DefaultLogoutSuccessHandler;
import pers.jason.wppm.security.core.properties.SecurityProperties;

/**
 * 
 * @author Jason
 * @Date 2018-10-30 09:30
 *
 */
@Configuration
public class BrowserBeanConfig {

	@Autowired	
	private DataSource dataSource;

	@Autowired
	private SecurityProperties securityProperties;
	
	/**
	 * 对用户的token操作（从数据库中存储、取出），实现记住我的功能
	 * @return
	 */
	@Bean
	public PersistentTokenRepository persistentTokenRepository() {
		JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
		tokenRepository.setDataSource(dataSource);
		//tokenRepository.setCreateTableOnStartup(true);//首次启动的时候创建表
		return tokenRepository;
	}

	@Bean
	@ConditionalOnMissingBean(LogoutSuccessHandler.class)
	public LogoutSuccessHandler logoutSuccessHandler() {
		LogoutSuccessHandler logoutSuccessHandler = new DefaultLogoutSuccessHandler(securityProperties.getBrowser().getLogoutPage());
		return  logoutSuccessHandler;
	}

	/**
	 * 对密码加密解密
	 * @return
	 */
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
}
